package com.rockbb.common.simpleframe.dispatcher;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.rockbb.common.simpleframe.action.ActionContainer;
import com.rockbb.common.simpleframe.action.ActionContext;
import com.rockbb.common.simpleframe.config.SimpleConfig;

public class Dispatcher implements Filter {

	private static Logger logger = Logger.getLogger(Dispatcher.class);
	private String attribute = null;
	private FilterConfig filterConfig = null;
	private static String ext =SimpleConfig.getConfig("extension");

	// Initialise the dispatcher filter rule
	private static String regex;
	static 
	{
		if (ext==null || ext.length() == 0 || ext.length() == 1)
		{
			ext = "";
			regex = ".*?/[^\\.]*?$";
		}
		else
		{
			if (ext.charAt(0)!='.') {ext = "."+ext;}
			regex = ".*?\\."+ ext.substring(1) + "$";
		}
	}

	public void init(FilterConfig filterConfig) throws ServletException 
	{
		this.filterConfig = filterConfig;
		this.attribute = filterConfig.getInitParameter("attribute");
	}

	public void destroy() 
	{
		this.attribute = null;
		this.filterConfig = null;
	}

	public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException 
	{
		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) res;
		String servletPath = request.getServletPath();

		if (servletPath.matches(regex))
		{
			long startTime = System.currentTimeMillis();

			String name = servletPath.substring(1, servletPath.length() - ext.length());

			ActionContext context = SimpleConfig.getActionContext(name);

			if (context != null) 
			{
				ActionContainer container = new ActionContainer(context, request, response);
				container.process();
			}
			long stopTime = System.currentTimeMillis();
			logger.info( "Dispatcher: " + servletPath + ": " + (stopTime - startTime) + " milliseconds");
		} 
		else 
		{
			chain.doFilter(req, res);
		}
	}

}
